package util;

import com.google.zxing.*;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.sun.javaws.exceptions.ErrorCodeResponseException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/testQRCodeUtil")
public class testQRCodeUtil extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置页面编码
        response.setContentType("image/png");
        request.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition","attachment; filename=xiaochen.png");

        String format="png";
        String content="超级喜欢小陈";
        //设置额外参数
        Map map = new HashMap();
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        map.put(EncodeHintType.MARGIN,2);
        map.put(EncodeHintType.CHARACTER_SET,"utf-8");

        try {
            BitMatrix encode =  new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,400,400,map);
            int width=encode.getWidth();
            int hight=encode.getHeight();
            BufferedImage image = new BufferedImage(width,hight,BufferedImage.TYPE_INT_RGB);
            for (int x=0;x<width;x++)
            {
                for (int y=0;y<hight;y++)
                {
                    image.setRGB(x,y,encode.get(x,y)? 0xFF000001 : 0xFFFFFFFF);
                }
            }

            ImageIO.write(image, format, response.getOutputStream());//输出二维码

            /*ImageIO.write(bufferedImage, "png", new File("E:\\node.png"));//输出带logo图片*/
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

}
